package _binary_search;

/**
 * 704. 二分查找
 */
public class No704 {
    /**
     * 1. 闭区间
     */
    public int search1(int[] nums, int target) {
        int n = nums.length;
        int left = 0, right = n - 1; // 表示闭区间[left,right]
        while (left <= right) { // 区间不为空
            int mid = left + (right - left >> 1); // mid向下取整
            if (nums[mid] == target) return mid;
            else if (nums[mid] < target) left = mid + 1;
            else if (nums[mid] > target) right = mid - 1;
        }
        return -1;
    }

    /**
     * 2. 左闭右开
     */
    public int search2(int[] nums, int target) {
        int n = nums.length;
        int left = 0, right = n; // 表示闭区间[left,right)
        while (left < right) { // 区间不为空
            int mid = left + (right - left >> 1); // mid向下取整
            if (nums[mid] == target) return mid;
            else if (nums[mid] < target) left = mid + 1;
            else if (nums[mid] > target) right = mid;
        }
        return -1;
    }

    /**
     * 3. 开区间
     */
    public int search3(int[] nums, int target) {
        int n = nums.length;
        int left = -1, right = n; // 表示闭区间(left,right)
        while (left + 1 < right) { // 区间不为空
            int mid = left + (right - left >> 1); // mid向下取整
            if (nums[mid] == target) return mid;
            else if (nums[mid] < target) left = mid;
            else if (nums[mid] > target) right = mid;
        }
        return -1;
    }
}
